//~ Project: wslds-blog File: LinkUtils.java Created date: Feb 21, 2012
package com.wslds.base.util;

import org.apache.commons.lang.StringUtils;

/**
 * 
 * @author $Author: donilan.qq@gmail.com $
 * @version $Revision: 83 $
 */
public class LinkUtils {
	public static final String SUFFIX = ".action";
	
	/**
	 * 生成链接地址
	 * @param contextPath - 域名地址
	 * @param prefix - 前缀地址，例如admin,front等
	 * @param controller - 如名
	 * @param action - 如名
	 * @return - some like www.ii2d.com/admin/controller/action.do
	 */
	public static String linkTo(String contextPath, String prefix, String controller, String action) {
		
		contextPath = addSlash(contextPath);
		prefix = addSlash(prefix);
		controller = StringUtils.trimToEmpty(controller);
		if(StringUtils.isNotBlank(action)) {
			controller = addSlash(controller);
		}
		String link = String.format("%s%s%s%s%s", contextPath, prefix, controller, action, SUFFIX);
		if(StringUtils.isNotBlank(controller)) {
			if(StringUtils.indexOf(link, "/") != 0 ) {
				link = "/" + link;
			}
		}
		return link;
	}
	
	/**
	 * @see {@link #linkTo(String, String, String, String)}
	 */
	public static String linkTo(String action) {
		return linkTo(null, null, null, action);
	}
	
	/**
	 * 生成一个html a标签
	 * @param link - 地址
	 * @param name - 显示名
	 * @param target - 目标_self, _blank
	 * @return - 一个标准的a标签
	 */
	public static String createLink(String link, String name, String target) {
		return String.format("<a href=\"%s\" target=\"%s\" >%s</a>", link, StringUtils.isNotBlank(target)? target: "_self", name);
	}
	
	/**
	 * @see {@link #createLink(String, String, String)}
	 */
	public static String createLink(String link, String name) {
		return createLink(link, name, null);
	}
	
	private static String addSlash(String path) {
		return StringUtils.isNotBlank(path) ? StringUtils.trimToEmpty(path) + "/": "";
	}
}
